import _projectConfig from '@/app.config.js'
// 根据环境切换配置
let _baseURL = _projectConfig.baseURL[_projectConfig.currentEnv];


//生成uuid
export function uuid() {
	let s = []
	let hexDigits = "0123456789abcdef"
	for (let i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
	}
	s[14] = "4" // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = "-"

	return s.join("")
}

//上传图片
export function upImg() {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1,
			sourceType: ["album"],
			success: async res => {
				if(res.tempFilePaths[0]){
					uni.showLoading({
					    title: `正在上传...`
					});
					uni.uploadFile({
						url: _baseURL.API_URL + '/util/upload', //仅为示例，非真实的接口地址
						filePath: res.tempFilePaths[0],
						name: 'file',
						success: (uploadFileRes) => {
							resolve(JSON.parse(uploadFileRes.data))
							uni.hideLoading();
						},
						fail() {
							uni.showToast({
							    icon: '上传失败',
							    title: text
							})
							uni.hideLoading();
						}
					});
				}
			},
		})
	})
}

//剩余空间即的高度
export function getWindHeight(dom) {
	return new Promise((resolve, reject) => {
		uni.getSystemInfo({
			success: res => {
				//顶部高度
				let topView = uni.createSelectorQuery().select(dom)
				topView.boundingClientRect(data => {
					let topViewHeight = data.height
					let phoneHeight = res.windowHeight //手机屏幕高度
					let getHeight = phoneHeight - topViewHeight //注意margin距离，
					resolve(getHeight)
				}).exec()
			}
		})
	})
}

// 安卓下载
export function downloadFile(item) {
	let progress = 0
	console.log('item=====>', item)
	const downloadTask = uni.downloadFile({
		url: item.packageUrl,
		success: file => {
			if (progress != 100) {
				uni.$emit('ON_DOWNLOAD_PROGRESS_CHANGE', -1)
				return
			}

			uni.saveFile({
				tempFilePath: file.tempFilePath, //临时路径
				success: function (res) {
					let upgrade_info = {
						tempFilePath: res.savedFilePath,
						version: item.version
					}
					uni.setStorageSync("UPGRADE_INFO", upgrade_info)
					plus.runtime.install(res.savedFilePath, { force: true },
						function () {
							plus.runtime.setBadgeNumber(0, { title: '', content: '' });
							if (uni.getSystemInfoSync().platform == 'ios') {
								plus.ios.import("UIApplication").sharedApplication().performSelector("exit")
							} else if (uni.getSystemInfoSync().platform == 'android') {
								plus.runtime.quit();
							}
						},
						function (e) {

						})
					plus.nativeUI.closeWaiting()
				}, fail(err) {
					uni.$emit('ON_DOWNLOAD_PROGRESS_CHANGE', -1)
				}
			});
		}
	})
	downloadTask.onProgressUpdate((res) => {
		if (res.progress > progress) {
			progress = res.progress
			uni.$emit('ON_DOWNLOAD_PROGRESS_CHANGE', res.progress)
		}
	})
}
